<?php
class FileAppController extends Controller
{
    public $layout = false;
        
    public function actionIndex()
    {
        $appId = isset($_GET["appId"]) ? intval($_GET["appId"]) : 0;
        $extension = isset($_GET["extension"]) ? Common::cleanQuery($_GET["extension"]) : "";
        $userId = isset($_GET["userId"]) ? intval($_GET["userId"]) : 0;              
        
        $game = App::getInfoApp($appId);
        $file = AppFile::getAppFileByExtension($appId, $extension);
        $user = User::getUserInfo($userId);    
  
        if(!empty($file) && !empty($game) && !empty($user)){
            $username =  $user["username"];
            $this->render("index", array("game"=>$game, "file"=>$file, "username"=>$username,"userId"=>$userId));    
        } else {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo "Link không tồn tại";   
        }       
    }
    
    public function actionDownload()
    {
        $gameId = isset($_GET["appId"]) ? intval($_GET["appId"]) : 0;
        $userId = isset($_GET["userId"]) ? intval($_GET["userId"]) : 0;
        $extension = isset($_GET["extension"]) ? Common::cleanQuery($_GET["extension"]) : "";
        $user = User::getUserInfo($userId);
        $game = App::getInfoApp($gameId);
   
        if(!empty($gameId) && !empty($game) && !empty($user)){   
             $username =   $user["username"];
            // check extension
            
            if(!empty($extension)) {
                switch ($extension){
                     case "jar":
                     case "jad":
                     case "apk":
                     case "ipa":
                           $url = $this->getFileGameByExtension($game,$user,$extension);
                     break;
                     default:
                          $url = $this->getFileGameByExtension($game,$user,"jar");
                     break;
                }
            }else{
                // detech device
                $detect = new Mobile_Detect;
                $url = Url::createUrl("/fileApp/index", array("userId"=>$userId, "alias"=>$game["alias"], "appId"=>$game["id"]));  
                
                if($detect->isMobile()){
                      // check ios
                         $check = $detect->{'is'."iOS"}();
                         if($check){
                                $extension = "ipa" ;
                                $url = $this->getFileGameByExtension($game,$user,$extension); 
                                $urlplist = substr($url,0,strrpos($url,".")).".plist"; 
                                $url="itms-services://?action=download-manifest&url=".$urlplist ;  
                                //var_dump($url);die;
                         }
                      // check apk
                       $check = $detect->{'is'."AndroidOS"}();
                         if($check){
                                $extension = "apk" ;
                                $url = $this->getFileGameByExtension($game,$user,$extension);   
                         }
                      // check java
                       $check = $detect->{'is'."JavaOS"}();
                         if($check){
                                $extension = "jar" ;
                                $url = $this->getFileGameByExtension($game,$user,$extension);   
                         }
                        // check java
                       $check = $detect->{'is'."WindowsPhoneOS"}();
                         if($check){
                             
                         }
                }
            }   
            
           $this->redirect($url);   
        }else{
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo "Link không tồn tại";   
        }
    }
    
    public function actionDownloadFile()
    {
       
        $fileId = isset($_GET["fileId"]) ? intval($_GET["fileId"]) : 0;
        $userId = isset($_GET["userId"]) ? Common::cleanQuery($_GET["userId"]) : "";
        $user = User::getUserInfo($userId);   
        $file = AppFile::getAppFileById($fileId);
        
        if(!empty($fileId)  && !empty($file) &&!empty($user)){
            /* update count download file */
            $game = App::getInfoApp($file["appId"]);
            $result = AppFile::UpdateDownload($file["appId"], $file["id"]);
            $url_file = Common::getImageDomain($file["filename"],"user/" . $user["username"] . "/app","","",2);
            $folderJarDes = ConstantsUtil::DOCUMENT_ROOT."upload/user/".$user["username"]."/app/";
            $fileSource  = ConstantsUtil::DOCUMENT_ROOT.Common::getFileLocal($file["filename"], "app",$game["create_date"], "",3);
            $appId = $file["appId"];
           
            $fileAppBuild = ConstantsUtil::DOCUMENT_ROOT."upload/user/".$user["username"]."/app/".$file["filename"];
          
            if(!file_exists( $fileAppBuild )){
                $extension = substr(strrchr($file["filename"], "."), 1);
                $filename_response = substr($file["filename"],0,strrpos($file["filename"],"."));
                
                switch ($file["extension"]){
                    case "jad":
                    case "jar":
                        BuildFile::buildFileJava($fileSource,$folderJarDes,$appId,$user["refCode"],$file["filename"],$user["username"],0,$url_file);
                        BuildFile::downloadFile($url_file,$filename_response,$extension);
                    break;
                    case "apk":
                        BuildFile::buildAppAPK($fileSource,$folderJarDes,$appId,$file["filename"],$user["username"],$user["refCode"]);
                        BuildFile::downloadFile($url_file,$filename_response,$extension);
                    break;
                    case "ipa":
                         BuildFile::buildAppIPA($fileSource,$folderJarDes,$appId,$file["filename"],$file["refcode_path"],$user["username"],$user["refCode"]);
                         BuildFile::downloadFile($url_file,$filename_response,$extension);
                    break;
                }
               
            }else{
                $extension = substr(strrchr($file["filename"], "."), 1);
                $filename_response = substr($file["filename"],0,strrpos($file["filename"],"."));
                BuildFile::downloadFile($url_file,$filename_response,$extension); 
            }
        } else {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo "Link không tồn tại";   
        }        
    }
    
    function getFileGameByExtension($game,$user,$extension){
        $rowGameFiles = AppFile::getAllAppFileByExt($game["id"],$extension);
        $url = Url::createUrl("/fileApp/index", array("username"=>$user["username"], "alias"=>$game["alias"], "appId"=>$game["id"]));  
     
        if(count($rowGameFiles)>=1){
            // have one file
             if(count($rowGameFiles)==1)
             {
                    $filename =  $rowGameFiles[0]["filename"];
                    $create_date =  $game["create_date"];
                    $filename = $rowGameFiles[0]["filename"];
                    $refcode_path =  $rowGameFiles[0]["refcode_path"];
                   
                    $url = Common::getImageDomain($filename, "user/" . $user["username"] . "/app", "", "", 2);   
                    $folderJarDes = ConstantsUtil::DOCUMENT_ROOT."upload/user/".$user["username"]."/app/";
                    $fileSource  = ConstantsUtil::DOCUMENT_ROOT.Common::getFileLocal($filename, "app",$create_date, "",3);
                    
                    AppFile::UpdateDownload($game["id"], $rowGameFiles[0]["id"]);
                    $fileAppBuild = ConstantsUtil::DOCUMENT_ROOT."upload/user/".$user["username"]."/app/".$filename;
                    
                    if(!file_exists( $fileAppBuild )){
                     
                            $extension = $rowGameFiles[0]["extension"];
                            $filename_response = substr($filename,0,strrpos($filename,"."));
                            switch ($extension){
                                case "jad":
                                case "jar":
                                    BuildFile::buildFileJava($fileSource,$folderJarDes,$game["id"],$user["refCode"],$filename,$user["username"],0,$url);
                                break;
                                case "apk":
                                    BuildFile::buildAppAPK($fileSource,$folderJarDes,$game["id"],$filename,$user["username"],$user["refCode"]);
                                break;
                                case "ipa":
                                     BuildFile::buildAppIPA($fileSource,$folderJarDes,$game["id"],$filename,$refcode_path,$user["username"],$user["refCode"]);
                                break;
                            }
                    } 
             }else{
                     $url = Url::createUrl("/fileApp/index", array("username"=>$username,"extension"=>$extension, "alias"=>$game["alias"], "appId"=>$game["id"]));
             }
        }
        
        return   $url;
    }
} 
?>
